<?php

/*
 * Website Application
 *
 * Warlock is free software. This version may have been modified pursuant
 * to the GNU General Public License, and as distributed it includes or
 * is derivative of works licensed under the GNU General Public License or
 * other free or open source software licenses.
 *
 * @package    warlock
 * @author     David Cole <neophyte@sourcetutor.com>
 * @license    GNU/GPL v2
 */

// Application Dependencies which may not already be included
using('Engine.Error');
using('Engine.Profiling');
using('Engine.Model');
using('Engine.Module');
using('Engine.Config');
using('Engine.Session');
using('Engine.User');
using('Engine.DAL');
using('Applications.IApplication');
using('Applications.Admin.IModule');

class Application_Admin extends IApplication
{
    /**#@+
     * Required Core Objects
     *
     * These are references to the core objects required by this
     * class.
     *
     * @access private
     * @var    object
     */
    var $_Error;
    var $_Profiler;
    var $_DAL;
    var $_Model;
    var $_Module;
    var $_Config;
    var $_Session;
    var $_Observer;
    var $_User;
    /**#@-*/

    function __construct()
    {
        // Get references to required objects
        $this->_Error     = &Vault::Get('Debug_Error');
        $this->_Profiler  = &Vault::Get('Debug_Profiling');
        $this->_DAL       = &Vault::Get('DAL');
        $this->_Model     = &Vault::Get('Model');
        $this->_Config    = &Vault::Get('Config');
        $this->_Session   = &Vault::Get('Session');
        $this->_User      = &Vault::Get('User');
        $this->_Observer  = &Vault::Get('Observer');
        $this->_Module    = &Vault::Get('Module');

        // Load plugins relevent to the Website application
        $this->_Profiler->Start('Load Plugins');
        $this->_Observer->LoadApplicationPlugins('Common');
        $this->_Observer->LoadApplicationPlugins('Admin');
        $this->_Profiler->Stop();
        
        // Change the theme to Admin
        $this->_Error->Log('Application : Admin :: Switching Theme to \'Admin\'', W_LOG_DEBUG);
        $this->_Model->Set('Theme', 'Admin');
    }

    function Run()
    {
        /*
         * Handle the user login and logout actions and make sure the user has the appropriate access
         * level to go further.
         */
        
        // Clear the user session data
        if (isset($_GET['logout']))
        {
        	if ($this->_User->IsLoggedIn())
        	{
	        	$this->_Model->Set('Page.Messages.Completed', array('Successfully Logged Out.'));
	            $this->_User->Logout();
        	}
        	else 
				$this->_Model->Set('Page.Messages.Information', array('You appear to be already logged out.'));
        }
        
        // Display login form if the user is not logged in or lacks admin panel rights
        if (!$this->_User->IsLoggedIn() || !$this->_User->HasAccess('admin'))
        {        	
            using('Library.Widgets.Form');            
            $form = new Form('login', '/admin/');
            $form->Add(new TextField(&$form, 'username', 'Username', null, null, true));
            $form->Add(new PasswordField(&$form, 'password', 'Password', null, null, true));

            if ($form->Submitted())
            {
            	if (!$form->Validate()) // User left one of the fields blank
            	{             		
            		$this->_Model->Set('Page.Messages.Error', array('Both the Username and Password fields are required.'));
            		$this->_Model->Body('library', $form->ToArray(), 'login', 'form');
            	}
            	else 
            	{
	                if ($this->_User->Login($_POST['username'], $_POST['password']))
	                {	                
	                	if ($this->_User->HasAccess('admin'))
	                    	$this->_Controller();
	                    else 
	                    {
	                		$this->_Model->Set('Page.Messages.Error', array('Please login as a user which has administrator rights.'));
	                    	$this->_Model->Body('library', $form->ToArray(), 'login', 'form');	                    	
	                    }
	                }	                    
	                else
	                {
	                	$this->_Model->Set('Page.Messages.Error', array('Username or Password Incorrect.'));
	                    $this->_Model->Body('library', $form->ToArray(), 'login', 'form');
	                }
            	}
                    
            }
            else // Form has yet to be submitted
                $this->_Model->Body('library', $form->ToArray(), 'login', 'form');
        }
        else // User is logged in and hass admin panel access
            $this->_Controller();
    }

    /**
     * _Controller
     * 
     * Main controller for the Admin application
     * 
     */
    function _Controller()
    {
        // Some general defaults
        $module = 'warlock';
        $action = array();
        $uri    = $this->_Model->Get('URI');

        /*
         * Process the URI looking for the requested
         * module and action
         */

        for ($i = 0, $imax = count($uri); $i < $imax; $i++)
        {
            if (strpos($uri[$i], ';'))
            {
                $parts = explode(';', $uri[$i]);

                switch ($parts[0])
                {
                    case 'module': $module = $parts[1];               break;
                    case 'action': $action = explode(',', $parts[1]); break;
                }
            }
        }

        /*
         * We should know the module and action at this point, attempt to load
         * the requested module and then perform the requested action.
         */

        if (!($mod = &$this->_Module->Get('Admin', $module)))
            $this->_Error->Log('Application : Admin :: Error Instancing Module \''.$module.'\'', W_LOG_CRIT);

        if (!$mod->PerformAction($action))
            $this->_Error->Log('Application : Admin :: Action \''.implode('_', $action).'\' does not exist in module \''.$module.'\'', W_LOG_CRIT);

    }
}

?>